public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;  //默认最大负载因子
    private static final int DEFAULT_SIZE = 8; //默认桶的大小

    //初始化哈希桶
    public HashBucket() {
        array = new Node[DEFAULT_SIZE];
    }


    //放元素
    public int put(int key, int value) {

        //1.遍历index数组下的链表，如果有相同的key则更新val
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                cur.value = value;
                return 1;
            }
            cur = cur.next;
        }

        //2.头插法擦插入节点
        Node node = new Node(key,value);
        node.next = array[index];
        array[index] = node;

        //3.重新计算当前的负载因子 是不是超过了 我们规定的负载因子
        if(loadFactor() >= LOAD_FACTOR) {
            //扩容
            resize();
        }
        return -1;
    }


    //扩容
    private void resize() {
        // write code here
        Node[] newArray = new Node[array.length * 2];

        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null) {
                int newindex = cur.key % newArray.length;

                //把当前节点 放到新的数组的 newindex 位置  头插法
                Node curN = cur.next;
                cur.next = newArray[newindex];
                newArray[newindex] = cur;
                cur = curN;

            }
        }
        array = newArray;

    }


    //计算负载因子
    private double loadFactor() {
        return size * 1.0 / array.length;
    }

    //取对应key的value值
    public int get(int key) {
        // write code here
        int index = key % array.length;
        Node cur = array[index];

        while (cur != null) {
            if(cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }
}